package plugins

import (
	"net/http"

	"github.com/gorilla/websocket"
)

type WersbocketServer struct {
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}
var clients = make(map[*Client]bool)

type Client struct {
	conn         *websocket.Conn // 连接实例
	isMainDevice bool            // 是否为主设备
}

func (WersbocketServer) SendMessageToMainDevice(message string) {
	for client := range clients {
		if client.isMainDevice {
			client.conn.WriteMessage(websocket.TextMessage, []byte(message))
		}
	}
}
func (WersbocketServer) InitWersbocket(port string) {
	http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			return
		}
		client := &Client{conn: conn, isMainDevice: false}
		clients[client] = true
		func() {
			defer delete(clients, client)
			defer conn.Close()
		}()
		for {
			messageType, p, err := conn.ReadMessage()
			if err != nil {
				break
			}
			err = conn.WriteMessage(messageType, p)
			if err != nil {
				break
			}
		}
	})
	http.ListenAndServe(":"+port, nil)
}
